﻿using System;
using System.Windows;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using WPNextTools.NConstant;
using System.Windows.Controls;
using WPNextTools.NHelper;
using System.Diagnostics;

namespace WPNextTools.NControls
{
    public class ExplodePhotoListBox : PhotoListBox
    {
        #region Fields
        private ExplodePhotoListBoxItem toppedContainer;
        private PhoneApplicationPage currentPage;
        internal PhotoListBoxState currentState = PhotoListBoxState.Normal;
        internal string explodeFolderCache;
        internal string explodeMp3Cache;
        internal string deleteIconCache;
        internal MediaElement ambienceSound;
        #endregion

        #region Event
        public event EventHandler ExpoldItemRemove;
        #endregion

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            ambienceSound = new MediaElement();
            ambienceSound.AutoPlay = true;
            ambienceSound.Visibility = Visibility.Collapsed;
        }

        #region DependencyProperties

        #region ExplodeSourceFolder
        public string ExplodeSourceFolder
        {
            get { return (string)GetValue(ExplodeSourceFolderProperty); }
            set { SetValue(ExplodeSourceFolderProperty, value); }
        }

        public static readonly DependencyProperty ExplodeSourceFolderProperty =
            DependencyProperty.Register("ExplodeSourceFolder", typeof(string), typeof(ExplodePhotoListBox), new PropertyMetadata(OnExplodeSourceFolderChanged));

        private static void OnExplodeSourceFolderChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            (sender as ExplodePhotoListBox).OnExplodeSourceFolderChanged(e);
        }

        private void OnExplodeSourceFolderChanged(DependencyPropertyChangedEventArgs e)
        {
            this.explodeFolderCache = (string)e.NewValue;
        }
        #endregion

        #region ExplodeMp3

        public string ExplodeMp3
        {
            get { return (string)GetValue(ExplodeMp3Property); }
            set { SetValue(ExplodeMp3Property, value); }
        }

        public static readonly DependencyProperty ExplodeMp3Property =
            DependencyProperty.Register("ExplodeMp3", typeof(string), typeof(ExplodePhotoListBox), new PropertyMetadata(null,OnExplodeMp3Changed));

        private static void OnExplodeMp3Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            (sender as ExplodePhotoListBox).OnExplodeMp3Changed(e);
        }

        private void OnExplodeMp3Changed(DependencyPropertyChangedEventArgs e)
        {
            this.explodeMp3Cache = (string)e.NewValue;
        }
        #endregion

        #region DeleteImage
        public string DeleteIcon
        {
            get { return (string)GetValue(DeleteIconProperty); }
            set { SetValue(DeleteIconProperty, value); }
        }

        public static readonly DependencyProperty DeleteIconProperty =
            DependencyProperty.Register("DeleteIcon", typeof(string), typeof(ExplodePhotoListBox), new PropertyMetadata(OnDeleteIconChanged));

        private static void OnDeleteIconChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            (sender as ExplodePhotoListBox).OnDeleteIconChanged(e);
        }

        private void OnDeleteIconChanged(DependencyPropertyChangedEventArgs e)
        {
            deleteIconCache = (string)e.NewValue;
        }
        #endregion
        
        #endregion

        #region LostFocus

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            if (toppedContainer != null && toppedContainer.preparedToExplode)
            {
                return;
            }
            BackToNormalState();
        }

        protected override void OnLoaded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("OnLoaded");
            base.OnLoaded(sender, e);
            this.scrollableContent.Children.Add(ambienceSound);
            ambienceSound.AutoPlay = true;
        }

        protected override void OnUnloaded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("OnUnloaded");
            base.OnUnloaded(sender, e);
            this.scrollableContent.Children.Remove(ambienceSound);
            ambienceSound.Source = null;
            ambienceSound.AutoPlay = false;
        }

        #endregion

        #region ScrollState
        protected override void SetScrollState(ScrollState newState)
        {
            base.SetScrollState(newState);
            ScrollState oldState = base.currentScrollState;
            if (oldState == ScrollState.NotScrolling && newState == ScrollState.Scrolling)
            {
                if (this.currentState == PhotoListBoxState.Explode)
                {
                    if (this.toppedContainer.IsBusy)
                    {
                        this.toppedContainer.GoToBottomState();
                    }
                }
                return;
            }
        }
        #endregion
       
        #region ContainerForItem

        protected override void RealizedNewContainerOverride(PhotoListBoxItem container)
        {
            base.RealizedNewContainerOverride(container);
            if (this.currentState == PhotoListBoxState.Explode)
            {
                ((ExplodePhotoListBoxItem)container).GoToBottomState();
            }
        }

        protected override void RecoveryContainerOverride(PhotoListBoxItem container)
        {
            base.RecoveryContainerOverride(container);
            if (this.currentState == PhotoListBoxState.Explode)
            {
                ((ExplodePhotoListBoxItem)container).BackToNormal();
            }
        }

        /// <summary>
        /// 这个地方重写是为了在爆炸版中的Item为ExpldePhotoListBoxItem具备爆炸的功能
        /// </summary>
        /// <returns></returns>
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ExplodePhotoListBoxItem();
        }

        #endregion

        #region ItemOperate

        #region ItemHold
        internal void OnItemHold(ExplodePhotoListBoxItem holdContainer)
        {
            if (this.currentState != PhotoListBoxState.Explode && base.currentScrollState != ScrollState.Scrolling)
            {
                AttachToPageEvents();
                //设置图片墙控件的状态为爆炸状态
                this.currentState = PhotoListBoxState.Explode;
                //设置爆炸声音源文件
                //ambienceSound.Source = new Uri(explodeMp3Cache, UriKind.Relative);
                //关灯
                //base.scrollableContent.Background = ColorHelper.TranslateColor("FFF2EFED");
                //选中的进入顶部模式
                holdContainer.GoToToppedState();
                // 保存顶部容器
                this.toppedContainer = holdContainer;
                //设置删除icon
                //SetDeleteImage();
                //设置选中项
                base.SelectedItem = holdContainer.associatedDataItem.Value;
                //其余置为底部模式
                for (int i = 0; i < this.realizedItems.Count; i++)
                {
                    ExplodePhotoListBoxItem container = (ExplodePhotoListBoxItem)base.realizedItems[i];
                    if (!object.Equals(holdContainer, container))
                    {
                        container.GoToBottomState();
                    }
                }
            }
        }
        #endregion

        #region ItemTap
        protected override void OnItemTapOverride(PhotoListBoxItem tapedItem)
        {
            ExplodePhotoListBoxItem oldTopedItem = this.toppedContainer;
            if (this.currentState == PhotoListBoxState.Explode && ((ExplodePhotoListBoxItem)tapedItem).ItemState != ItemState.Topped && base.currentScrollState != ScrollState.Scrolling)
            {
                ((ExplodePhotoListBoxItem)tapedItem).GoToToppedState();
                toppedContainer = (ExplodePhotoListBoxItem)tapedItem;
                //如果原来顶部的容器仍然存在并且不等于当前选中的容器(如果两者相等的话再把他至于底部则出现了抵消的效果)
                if (oldTopedItem.IsBusy && oldTopedItem != tapedItem)
                {
                    oldTopedItem.GoToBottomState();
                }
            }
            else
            {
                base.OnItemTaped(tapedItem);
            }
        }

        #endregion

        #endregion

        #region PageEvents
        private void AttachToPageEvents()
        {
            PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (frame != null)
            {
                currentPage = frame.Content as PhoneApplicationPage;
                currentPage.BackKeyPress += OnBackKeyPress;
            }
        }

        private void DetachFromPageEvents()
        {
            if (currentPage != null)
            {
                currentPage.BackKeyPress -= OnBackKeyPress;
                currentPage = null;
            }
        }

        void OnBackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.currentState == PhotoListBoxState.Explode)
            {
                e.Cancel = true;
                this.BackToNormalState();
            }
        }

        #region BackToNormal
        public void BackToNormalState()
        {
            if (this.currentState == PhotoListBoxState.Explode)
            {
                this.currentState = PhotoListBoxState.Normal;
                this.scrollableContent.Background = new SolidColorBrush(Colors.Transparent);
                for (int i = 0; i < this.realizedItems.Count; i++)
                {
                    ((ExplodePhotoListBoxItem)this.realizedItems[i]).BackToNormal();
                }
                DetachFromPageEvents();
            }
        }
        #endregion

        #endregion

        #region ExplodDeleteImage
        internal virtual void OnDeleteImageClick()
        {
            //播放删除动画
            if (this.ExpoldItemRemove != null)
            {
                this.ExpoldItemRemove.Invoke(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// 在删除的过程当中
        /// </summary>
        internal void FreezeBottom()
        {
            foreach (ExplodePhotoListBoxItem container in this.realizedItems)
            {
                if (container.ItemState == ItemState.Bottomed)
                {
                    container.IsHitTestVisible = false;
                }
            }
        }

        internal void UnFreezeBottom()
        {
            foreach (ExplodePhotoListBoxItem container in this.realizedItems)
            {
                if (container.ItemState == ItemState.Bottomed && !container.IsHitTestVisible)
                {
                    container.IsHitTestVisible = true;
                }
            }
        }
        #endregion

        #region GetStateMethod

        public PhotoListBoxState GetCurrentState()
        {
            return this.currentState;
        }
        #endregion
    }
}
